package heap

import (
	"database/sql"
	"game/game-db/mysql/dao"
	"game/readygo/quickstart/repository"
)

type IPlayerOneToOneService[T IPlayerOneToOneEntity] interface {
	GetEntity(playerId int64) T              //获取玩家的数据
	CreateWhenNull(playerId int64) (T, bool) //创建玩家的实体数据
}

type PlayerOneToOneService[T IPlayerOneToOneEntity] struct {
	IRepository repository.IRepository[T]
	iService    IPlayerOneToOneService[T]
}

func (t *PlayerOneToOneService[T]) InitRepository(db *sql.DB, service IPlayerOneToOneService[T], entityTemplate T) {
	iDao := dao.NewDefaultBaseDao(db, entityTemplate)
	t.IRepository = repository.NewCacheRepository(iDao, entityTemplate)

	t.iService = service
}

// 获取玩家数据
func (t *PlayerOneToOneService[T]) GetEntity(playerId int64) T {
	entity, ok := t.IRepository.GetByKeys(playerId)
	if ok {
		return entity
	}
	entity, ok = t.iService.CreateWhenNull(playerId)
	if ok {
		entity.SetPlayerId(playerId)
		t.IRepository.Insert(entity)
	}
	return entity
}

func (t *PlayerOneToOneService[T]) Update(entity T) {
	t.IRepository.Update(entity)
}
